<%@ page import="es.onlysolutions.arq.core.configuration.Configuracion" %>
<%@ page import="es.onlysolutions.gs.comm.utils.IConstantes" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN\" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="arq" uri="/tld/arquitectura.tld" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="display" uri="http://displaytag.sf.net/el" %>
<%@ taglib prefix="dynamic" uri="/tld/dynamic.tld" %>

<html>
<head>
<jsp:include page="Head.jsp"/>

<!--Round the menu tabs-->
<script type="text/javascript">

    window.onload = function()
    {
        Nifty("ul#nav a", "small transparent top");
        Nifty("videoBoxId", "big");
    }
    function backToList()
    {
        history.go(-1)
    }

</script>

<script type="text/javascript">

//The developer key for the YouTube API.
var yourDevKey = '<%=Configuracion.getString(IConstantes.YOUTUBE.YOUTUBE_DEVELOPER_KEY)%>';

//The player.
var ytplayer;

//the you tube id of the video.
var youTubeVideoId = '<c:out value="${command.video.youTubeId}"/>';

//Set the inner HTML of the element with elementId. The styleClass is optional and is to set especific styles.
function updateHTML(elementId, value, styleClass)
{
    var element = document.getElementById(elementId);
    if( element )
    {
        element.innerHTML = value;
        if( styleClass != null )
        {
            element.className = styleClass;
        }
    }
}

//Add this video to the favourite list of the user.
//Function that execute a JSON call to the server to add this YouTube video to the personal list of the user.
function addToMyFavorites()
   {
   if( confirm('Add this video to your favourites?') )
   {
       var args = new Array();
       var userLogin = '<dynamic:user />';
       args[0] = "'" + youTubeVideoId + "'";
       args[1] = "'" + userLogin + "'";
       jsonEntityArrayCall( "videoFacade", "addVideo", args, cb_addToFavourites  );
   }
}

//Call back to the JSON call to add the video to the user favourites.
function cb_addToFavourites( result, exception )
{
   if( exception )
   {
       alert( exception );
   }
   else
   {
       if( result == 0 ) //OK
       {
           alert('OK!');
       }
       else if( result == 1 ) //No user
       {
           alert('Ooops! We don not know who are you. Are you logged in?');
       }
       else if( result == 2 ) //Video already added.
       {
           alert('This video was already added to your favourites!');
       }
   }
}

//Callback called when the player is ready. Here we cue the video and set intervals to refresh the info.
function onYouTubePlayerReady(playerId)
{
    if( youTubeVideoId != null && youTubeVideoId.length > 0 )
    {
        ytplayer = document.getElementById("myytplayer");
        ytplayer.cueVideoById(youTubeVideoId, 0);

        setInterval(updatePlayerInfo, 250);
        updatePlayerInfo();
        ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
    }
}

//Update the player state with the name of the current state.
function onPlayerStateChange(newState)
{
    if( newState == -1 ) //
    {
        updateHTML("playerstate", "Unstarted", null);
    }
    else if( newState == 0 )
    {
        updateHTML("playerstate", "Ended", null);
    }
    else if( newState == 1 )
    {
        updateHTML("playerstate", "Playing", null);
    }
    else if( newState == 2 )
    {
        updateHTML("playerstate", "Paused", null);
    }
    else if( newState == 3 )
    {
        updateHTML("playerstate", "Buffering...", null);
    }
    else if( newState == 5 )
    {
        updateHTML("playerstate", "Cued", null);
    }
}

//function set in the interval to update every time the info of the player.
function updatePlayerInfo()
{
    updateCurrentTime();
    updateLoadedVideo();
}

//Update the percetaje of the video that is loaded.
function updateLoadedVideo()
{
    var bytes = getBytesLoaded();
    var totalBytes = getBytesTotal();
    var completedPercentaje = (bytes*100)/totalBytes;
    if( bytes > 0 )
    {
        updateHTML("bytesLoaded", Math.ceil(completedPercentaje) + " %", "videoBytesStyle")
    }
}

//Update the percentaje of time consumed of the video.
function updateCurrentTime()
{
    var totalTime = getDuration();
    var currentTime = getCurrentTime();
    var completedTime = (currentTime*100) / totalTime;
    updateHTML("currentTime", Math.ceil(completedTime) + " %", "videoTimeStyle");
}

// functions for the api calls
function loadNewVideo(id, startSeconds)
{
    if (ytplayer)
    {
        ytplayer.loadVideoById(id, startSeconds);
    }
}


function play()
{
    if (ytplayer)
    {
        ytplayer.playVideo();
    }
}

function pause()
{
    if (ytplayer)
    {
        ytplayer.pauseVideo();
    }
}


//Reset the player to the second 0 and pause it.
function stop()
{
    if (ytplayer)
    {
        ytplayer.seekTo(0, true);
        pause();
    }
}

function getPlayerState()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getState();
    }
    return returnValue;
}

function getBytesLoaded()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getVideoBytesLoaded();
    }
    return returnValue;
}

function getBytesTotal()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getVideoBytesTotal();
    }
    return returnValue;
}

function getCurrentTime()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getCurrentTime();
    }
    return returnValue;
}

function getDuration()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getDuration();
    }
    return returnValue;
}

function getStartBytes()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getVideoStartBytes();
    }
    return returnValue;
}

function mute()
{
    if (ytplayer)
    {
        ytplayer.mute();
    }
}

function unMute()
{
    if (ytplayer)
    {
        ytplayer.unMute();
    }
}


function setVolume(newVolume)
{
    if (ytplayer)
    {
        ytplayer.setVolume(newVolume);
    }
}

function getVolume()
{
    var returnValue;
    if (ytplayer)
    {
        returnValue = ytplayer.getVolume();
    }
    return returnValue;
}

function clearVideo()
{
    if (ytplayer)
    {
        ytplayer.clearVideo();
    }
}



</script>

</head>
<body id="page" >

<c:set var="currentPage" value="" scope="request" />
<jsp:include page="Menu.jsp"/>

<br><br><br><br><br><br>
<!--Init video config-->

<center>
    <arq:errors classTable="tablaErrores" visibility="global" printModel="table" />
    <table align="center" class="videoBox" id="videoBoxId" >
        <tr align="center">
            <td align="center">
                <div id="ytapiplayer">
                    You need Flash player 8+ and JavaScript enabled to view this video.
                </div>
                <script type="text/javascript">
                    var params = { allowScriptAccess: "always", bgcolor: "#cccccc" };
                    var atts = { id: "myytplayer" };
                    swfobject.embedSWF("http://gdata.youtube.com/apiplayer?key=" + yourDevKey + "&enablejsapi=1&playerapiid=ytplayer",
                            "ytapiplayer", "400", "300", "8", null, null, params, atts);
                </script>
            </td>
            <td>
                <table>
                    <tr>
                        <td><dynamic:flashButton text="Play" link="play()" color="green" width="150" height="30" /></td>
                    </tr>
                    <tr>
                        <td><dynamic:flashButton text="Pause" link="pause()" color="grey" width="150" height="30" /></td>
                    </tr>
                    <tr>
                        <td><dynamic:flashButton text="Stop" link="stop()" color="red" width="150" height="30" /></td>
                    </tr>
                    <tr>
                        <td><dynamic:flashButton text="Mute" link="mute()" color="blue" width="150" height="30" /></td>
                    </tr>
                    <tr>
                        <td><dynamic:flashButton text="Unmute" link="unMute()" color="blue" width="150" height="30" /></td>
                    </tr>
                    <tr>
                        <td><dynamic:flashButton text="Add to Favourites" link="addToMyFavorites()" color="blue" width="150" height="30" /></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                State:&nbsp;<span id="playerstate" style="font-style:italic;">Wait</span>&nbsp;&nbsp;
                Time consumed:&nbsp;<span id="currentTime" class="videoTimeStyle">0 %</span>&nbsp;&nbsp;
                Loaded video:&nbsp;<span id="bytesLoaded" class="videoBytesStyle">0 %</span>
        </tr>
    </table>
    <br/>
    <table align="center">
        <tr>
            <td>
                <dynamic:flashButton text="Back" link="backToList()" color="red" height="60" width="300" />
            </td>
        </tr>
    </table>
</center>

<!--End video config-->



</body>
</html>